const Service = require("egg").Service;

class RoleService extends Service {
  // 获取角色列表
  async getRoleList() {
    const { app } = this;
    try {
      return await app.model.Role.findAll({
        attributes: ["id", "name", "created", "edited"],
        where: { delFlag: 0 },
        include: [
          {
            model: app.model.Permission,
            attributes: ["id", "name","title","path"],
            through:{attributes:[]} //不查中间表
          }
        ],
      });
    } catch (err) {
      throw new Error(err);
    }
  }

  /**
   * 添加修改角色
   * @param {*} param0
   * @returns
   */
  async modifyRole({ id, name, creator = null, editor = null }) {
    const { app } = this;
    try {
      if (!id) {
        return await app.model.Role.create({
          name,
          creator,
        });
      } else {
        const exit = await app.model.Role.findByPk(id);
        if (!exit) {
          this.ctx.logger.debug(`根据${id}无法查询到模板`);
          throw new Error("无法查询到模板");
        }
        exit.update({ name, editor });
        return true;
      }
    } catch (err) {
      console.log(err);
      throw new Error(err);
    }
  }

  /**
   * 删除角色
   * @param {*} id
   * @returns
   */
  async deleteRole(id) {
    const { app, ctx } = this;
    let transaction = null;
    try {
      transaction = await ctx.model.transaction();
      await app.model.Role.update(
        {
          delFlag: 1,
        },
        {
          where: {
            id,
          },
          transaction,
        }
      );
      /**
       *
       * 批量删除
       */
      await app.model.UserRole.destroy({
        where: {
          roleId: id,
        },
        transaction
      });
      await app.model.RolePermission.destroy({
        where: {
          roleId: id,
        },
        transaction
      });

      await transaction.commit();
      return true;
    } catch (err) {
      await transaction.rollback();
      throw new Error(err);
    }
  }

  async findRoleSelfPermissions(roleId){
    const { app } = this;
    try {
      return await app.model.RolePermission.findAll({
        attributes: ["id",  "permissionId","roleId" ],
        where: { roleId: roleId },
      });
    } catch (err) {
      console.log(err);
      throw new Error(err)
    }
  }

  async roleAddPermission(roleId, permissionIds) {
    const { app } = this;
    try {
      const rolePermissions = await app.model.RolePermission.findAll({
        attributes: ["id", "roleId", "permissionId"],
        where: { roleId: roleId },
      });
      const roleIdS = rolePermissions.map(rolePermission => rolePermission.roleId)
      /**
       * 
       * 批量删除
       */
      let rows = await app.model.RolePermission.destroy({
        where: {
          roleId: roleIdS
        }
      })
      /**
       * 批量修改
       */
      let list = []
      permissionIds.forEach(permissionId => {
        list.push({
          permissionId, roleId
        })
      });
      const exit = await app.model.RolePermission.bulkCreate(list);
      return exit
    } catch (error) {
      throw new Error(error)
    }

  }

}

module.exports = RoleService;
